package com.indexingsystem.boss.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;

import com.indexingsystem.boss.common.session.CurrentUser;
import com.indexingsystem.boss.entity.Pusers;
import com.indexingsystem.boss.logback.LogCvt;
import com.indexingsystem.boss.token.manager.TokenManager;

import net.sf.json.JSONObject;

/**
 * Shiro Filter 工具类.
 * 
 * @author Administrator
 *
 */
public class ShiroFilterUtils {
	final static Class<? extends ShiroFilterUtils> CLAZZ = ShiroFilterUtils.class;
	// 登录页面
	static final String LOGIN_URL = "/login";
	// 踢出登录提示
	// final static String KICKED_OUT = "/open/kickedOut.shtml";
	// 没有权限提醒
	 final static String UNAUTHORIZED = "/open/unauthorized.shtml";

	/**
	 * 是否是Ajax请求
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isAjax(ServletRequest request) {
		return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
	}

	/**
	 * response 输出JSON
	 * 
	 * @param hresponse
	 * @param resultMap
	 * @throws IOException
	 */
	public static void out(ServletResponse response, Map<String, String> resultMap) {

		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.println(JSONObject.fromObject(resultMap).toString());
		} catch (Exception e) {
			LogCvt.error("输出JSON报错。", e);
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
	}
	
	public static void goLoginPage(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
			response.setCharacterEncoding("UTF-8");
//			out = response.getWriter();
			response.sendRedirect("/view/index.html#/login");
//			response.
//			out.println("view/index.html#/login");
		} catch (Exception e) {
			LogCvt.error("输出JSON报错。", e);
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
//		return "redirect:/view/index.html#/login";
	}
}
